package com.project.workjob.schedule;


import com.project.workjob.dto.ConfigDto;
import com.project.workjob.dto.GjxlParam;
import com.project.workjob.dto.HolidayDto;
import com.project.workjob.entity.Gjxl;
import com.project.workjob.entity.GjxlYb;
import com.project.workjob.entity.SkbDay;
import com.project.workjob.entity.WorkCalendar;
import com.project.workjob.service.GjxlService;
import com.project.workjob.service.GjxlYbService;
import com.project.workjob.service.SkbDayService;
import com.project.workjob.service.WorkCalendarService;
import com.project.workjob.util.GjxlYbHttpResult;
import com.project.workjob.util.GjxlYbUtil;
import com.project.workjob.util.HolidayHttpResult;
import com.project.workjob.util.HttpUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * - 定时任务
 */
@Slf4j
@Component
@EnableScheduling
public class Scheduler {

    @Resource
    ConfigDto configDto;
    @Resource
    GjxlYbService gjxlYbService;
    @Resource
    GjxlService gjxlService;
    @Resource
    WorkCalendarService workCalendarService;
    @Resource
    SkbDayService skbDayService;

    // @Scheduled(cron = "0 5 0 * * ?")
    private void syncJob() {
        log.info("每天0点5分定时任务执行开始");
        try {
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            LocalDate now = LocalDate.now();

            List<SkbDay> list = skbDayService.getListForDay();
            if (list.size() > 0) {
                for (SkbDay skbDay : list) {
                    skbDay.setRq(new Date());
                }
                skbDayService.insert(list);
            }
        } catch (Exception e) {
            log.error("每天0点5分定时任务执行结束,执行失败：【{}】", e.getMessage());
        } finally {
            log.info("每天0点5分定时任务执行结束");
        }
    }

    // @Scheduled(cron = "0 0 0 6 * ?")
    private void syncGjxlYJob() {
        log.info("每月6日0点定时获取海致接口数据任务执行开始");
        LocalDate now = LocalDate.now();
        LocalDate nowFirstDay = now.minusDays(5);
        LocalDate lastMonthDay = nowFirstDay.minusMonths(1);
        LocalDate nowEndDay = now.minusDays(6);
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        String startDate = formatter.format(lastMonthDay);
        String endDate = formatter.format(nowEndDay);
        String url = configDto.getGjxlybHost() + "?report_time_start=" + startDate + "&report_time_end=" + endDate;
        HttpUtil httpUtil = new HttpUtil(url, configDto.getTimeout());
        String token = configDto.getToken();
        try {
            GjxlYbHttpResult result = httpUtil.getGjxlYbUrl(token);
            List<List<String>> dataList = result.getData().getResult().getValues();
            List<GjxlYb> gjxlYbList = GjxlYbUtil.getData(dataList);
            if (gjxlYbList != null && gjxlYbList.size() > 0) {
                gjxlYbService.deleteByDate(gjxlYbList.get(0).getReport_time());
                Calendar calendar = Calendar.getInstance();
                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                calendar.setTime(df.parse(gjxlYbList.get(0).getReport_time()));
                calendar.add(Calendar.MONTH, -1);
                String beforeDate = df.format(calendar.getTime());
                List<GjxlYb> gjxlYbList1 = gjxlYbService.getListByDate(beforeDate);
                if (gjxlYbList1.size() > 0) {
                    for (GjxlYb gjxlYb : gjxlYbList) {
                        for (GjxlYb gjxlYb1 : gjxlYbList1) {
                            if (gjxlYb.getNo2().equals(gjxlYb1.getNo2())) {
                                gjxlYb.setJgxlid(gjxlYb1.getJgxlid());
                                break;
                            }
                        }
                    }
                }
                List<GjxlYb> gjxlYbNullList = gjxlYbList.stream().filter(item -> item.getJgxlid() == null).collect(Collectors.toList());
                if (gjxlYbNullList.size() > 0) {
                    for (GjxlYb gjxlYb : gjxlYbNullList) {
                        GjxlParam gjxlParam = new GjxlParam();
                        gjxlParam.setName(gjxlYb.getNo2());
                        List<Gjxl> gjxl1 = gjxlService.getJgxlidByName(gjxlParam);
                        if (gjxl1.size() > 0) {
                            gjxlYb.setJgxlid(gjxl1.get(0).getJgxlid());
                        }
                        if (gjxlYb.getJgxlid() == null) {
                            List<Gjxl> gjxl2 = gjxlService.getJgxlidByYgName(gjxlParam);
                            if (gjxl2.size() > 0) {
                                gjxlYb.setJgxlid(gjxl2.get(0).getJgxlid());
                            }
                        }
                    }
                }
                gjxlYbService.insert(gjxlYbList);
            }
        } catch (Exception e) {
            log.error("每月6日0点定时获取海致接口数据任务执行结束,执行失败：【{}】", e.getMessage());
        } finally {
            log.info("每月6日0点定时获取海致接口数据任务执行结束");
        }
    }

    // @Scheduled(cron = "0 30 0 5 * ?")
    private void syncWorkCalendarJob() {
        log.info("每月5日0点30分定时更新下月工作日历任务执行开始");
        LocalDate now = LocalDate.now();
        LocalDate next = now.plusMonths(1);
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMM");
        try {
            String url = configDto.getHolidayHost() + formatter.format(next);
            HttpUtil httpUtil = new HttpUtil(url, configDto.getTimeout());
            HolidayHttpResult result = httpUtil.getHolidayUrl();
            List<HolidayDto> holidayDtoList = result.getData().getList();
            if (holidayDtoList != null && holidayDtoList.size() > 0) {
                List<WorkCalendar> list = new ArrayList<>();
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
                for (HolidayDto dto : holidayDtoList) {
                    WorkCalendar entity = new WorkCalendar();
                    entity.setCalendar_date(sdf.format(df.parse(dto.getDate())));
                    entity.setDate_name(dto.getWeek_cn());
                    entity.setFlag(dto.getWeek());
                    list.add(entity);
                }
                workCalendarService.insert(list);
            }
        } catch (Exception e) {
            log.error("每月5日0点30分定时更新下月工作日历任务执行结束,执行失败：【{}】", e.getMessage());
        } finally {
            log.info("每月5日0点30分定时更新下月工作日历任务执行结束");
        }
    }
}
